package com.edu.chat.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-29 14:53
 **/

@Configuration
@EnableAsync
public class VectorizationThreadPoolConfig implements AsyncConfigurer {

	/**
	 * 文本向量化专用线程池
	 * 命名规则：vector-pool-{线程编号}
	 */
	@Bean(name = "vectorizationThreadPool")
	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

		// 根据服务器CPU核心数设置 (建议生产环境使用Runtime.getRuntime().availableProcessors())
		int corePoolSize = 3;    // 常驻线程数
		int maxPoolSize = 8;      // 最大线程数
		int queueCapacity = 50;   // 队列容量

		executor.setCorePoolSize(corePoolSize);
		executor.setMaxPoolSize(maxPoolSize);
		executor.setQueueCapacity(queueCapacity);
		executor.setThreadNamePrefix("vector-pool-");

		// 拒绝策略 (生产环境建议根据业务需求选择)
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

		// 允许核心线程超时关闭（根据业务需求设置）
		executor.setAllowCoreThreadTimeOut(false);

		// 线程空闲存活时间（秒）
		executor.setKeepAliveSeconds(60);
		executor.setTaskDecorator(new ContextCopyingDecorator());
		executor.initialize();
		return executor;
	}
}